package com.water_work_form.log;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.server.HttpServerRequest;
import com.water_work_form.entity.OperateLog;
import com.water_work_form.result.Result;
import com.water_work_form.service.OperateLogService;
import lombok.extern.java.Log;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
public class LogAspect {

    @Resource
    private OperateLogService operateLogService;

    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
    @Around("@annotation(autoLog)")
    public Object doAround(ProceedingJoinPoint joinPoint,AutoLog autoLog) throws Throwable{
        String name = autoLog.value();
        String date = DateUtil.now();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getRemoteAddr();
        OperateLog operateLog = new OperateLog(null,name,date,ip);
        operateLogService.save(operateLog);
        Result result = (Result) joinPoint.proceed();
        return result;
    }

}
